<?php
/**
 * @author Thanhpv
 * @date Wed 06/09/2014
 *
 */
class TwoImages extends CI_Controller {
	public function __construct() {
		parent::__construct ();
		$this->load->library ( 'session' );
	}
	public function index() {
		$this->load->Model ( "mimage" );
		
		session_start ();
		$userId = "";
		$imageName = "";
		if (isset ( $_SESSION ["userId"] ))
			$userId = $_SESSION ["userId"];
		else
			redirect ( $this->config->item ["RedirectURL"] );
		if (isset ( $_SESSION ["imageName"] ))
			$imageName = $_SESSION ["imageName"];
		else {
			$_SESSION ["imageName"] = "default.jpg";
			$imageName = $_SESSION ["imageName"];
			// copy default image to userId folder
			$folderName = $userId;
			$destination = './UserUploads/' . $folderName;
			$mode = 0777;
			$mkdirError = ! is_dir ( $destination ) ? mkdir ( $destination, $mode ) : true;
			if (! $mkdirError) {
				$this->session->set_flashdata ( "Error", "There is an error with server" );
				redirect ( base_url ( "index.php/ImageUpload/ImageUpload/index" ) );
				return;
			}
			
			$copyFile = copy ( "./UserUploads/default.jpg", $destination . "/default.jpg" );
			if (! $copyFile) {
				$this->session->set_flashdata ( "Error", "There is an error with server" );
				redirect ( base_url ( "index.php/ImageUpload/ImageUpload/index" ) );
				return;
			}
		}
		// copy original image into wartermark one
		
		if(isset($_SESSION["imagePath"]))
			$size = $this->mimage->getSize($_SESSION["imagePath"]);
		else 
			$size = $this->mimage->getSize("./UserUploads/$userId/default.jpg");
		$data = (! isset ( $_SESSION ["isTwoImages"] )) ? array (
				'width' => $size [0],
				'height' => $size [1],
				'userId' => $userId,
				'imageName' => ((isset($_SESSION["imagePath"])))?$_SESSION ["imagePath"]:base_url()."./UserUploads/$userId/default.jpg"
		) : ((strcmp ( $_SESSION ["isTwoImages"], $imageName ) == 0) ? array (
				'width' => $size [0],
				'height' => $size [1],
				'userId' => $userId,
				'imageName' => ((isset($_SESSION["imagePath"])))?$_SESSION ["imagePath"]:base_url()."./UserUploads/$userId/default.jpg"
		) : array (
				'width' => $size [0],
				'height' => $size [1],
				'userId' => $userId,
				'imageName'=>"./UserUploads/$userId/default.jpg"
		));
		
		// resize uses $_SESSION["userId"] and $_SESSION["imageName"] so must be here
		$data["funcType"] = 1;
		$this->load->view ( 'FunctionTwoImages/index', $data );
	}
	public function backgroundProcess() {
		$this->load->Model ( "mimage" );
		if (isset ( $_POST )) {
			session_start ();
			$userId = $_SESSION ["userId"];
			if (isset ( $_FILES )) {
				// back to index
				// check error
				if (strcmp ( $_FILES ['backgroundImage'] ['name'], "" ) == 0) {
					$_SESSION ["backgroundImageName"] = "defaultBackground.jpeg";
					redirect ( base_url ( "index.php/FunctionTwoImages/TwoImages/index" ) );
					return;
				}
				if ($_FILES ['backgroundImage'] ['error'] > 0) {
					$this->session->set_flashdata ( "Error", "This background contains error" );
					redirect ( base_url ( "index.php/FunctionTwoImages/TwoImages/index" ) );
					return;
				}
				// check extension jpeg, jpg, png
				$fType = $_FILES ['backgroundImage'] ['type'];
				$allowedExtensions = array (
						"image/jpg",
						"image/jpeg" 
				);
				$extensionError = ! in_array ( $fType, $allowedExtensions );
				// check extension
				if ($extensionError) {
					$this->session->set_flashdata ( "Error", "This background extension is incorrect" );
					redirect ( base_url ( "index.php/FunctionTwoImages/TwoImages/index" ) );
					return;
				}
				// check size
				$fSize = $_FILES ['backgroundImage'] ['size'] / 1024 / 1024;
				if ($fSize > 1) {
					$this->session->set_flashdata ( "Error", "This background is too large" );
					redirect ( base_url ( "index.php/FunctionTwoImages/TwoImages/index" ) );
					return;
				}
				
				$folderName = $_SESSION ['userId'];
				$destination = 'UserUploads/' . $folderName;
				// Save file
				// Must be tmp_name, not name
				$typeOnly = str_replace("image/", "", $_FILES ['backgroundImage'] ['type']);
				if($typeOnly=="jpeg")
					$typeOnly = "jpg";
				
				if(isset($_SESSION["imagePath"]))
					$imageSize = $this->mimage->getSize($_SESSION["imagePath"]);
				else
					$imageSize = $this->mimage->getSize("./UserUploads/$userId/default.jpg");
				
				
				move_uploaded_file($_FILES["backgroundImage"]["tmp_name"], $destination."/".$_FILES ['backgroundImage'] ['name']);
				$_SESSION["backgroundImageName"] = $_FILES ['backgroundImage']['name'];
				$_SESSION["backgroundPath"] = $destination."/".$_SESSION["backgroundImageName"];
				$_SESSION["backgroundChanged"] = true;
				
				
				if(isset($_SESSION["backgroundPath"])){
					$backgroundPath = $_SESSION["backgroundPath"];
					$size = $this->mimage->getSize($backgroundPath);
				}
				else {
					$backgroundPath = "./UserUploads/defaultBackground.jpg";
					$size = $this->mimage->getSize("./UserUploads/$userId/defaultBackground.jpg");
				}
					
				
				$backgroundName = $_SESSION ['backgroundImageName'];
				//always resize background image to width 940
// 				if ($size [0] > 940) {
					$resizeWidth = 940;
					$resizeHeight = (63 * $size [1] / 94 > 475) ? 63 * $size [1] / 94 : 475;
					$tmp = $resizeWidth . "x" . $resizeHeight;
					
					$command = "convert " . $backgroundPath . " -resize $tmp! " . "./$destination/$backgroundName";
					exec ( $command );
					//delete in server
					echo "</br>" . $command . "</br>";
// 				}
				
				$outputName = $backgroundName;
				$outputNameOnly = preg_replace("/\.\w+/", "", $outputName);
				
				$cloudUpload = \Cloudinary\Uploader::upload("./$destination/$backgroundName", array("public_id" => "UserUploads/$userId/$outputNameOnly"));
				$_SESSION["backgroundPath"] = $cloudUpload['url'];
				
				// Check size background < size image
				if ($size [0] < $imageSize [0] || $size [1] < $imageSize [1]) {
					unset ( $_SESSION ["backgroundImageName"] );
					unset ( $_SESSION ["backgroundChanged"] );
					$this->session->set_flashdata ( "Error", "The background is too small" );
					redirect ( base_url ( "index.php/FunctionTwoImages/TwoImages/index" ) );
					return;
				}
			}
			redirect ( base_url ( "index.php/FunctionTwoImages/TwoImages/index" ) );
		}
	}
	public function process() {
		$this->load->Model ( "mimage" );
		if (isset ( $_POST )) {
			session_start ();
			
			$this->mimage->twoImages ( $_POST );
			
			redirect ( base_url ( "index.php/FunctionTwoImages/TwoImages/index" ) );
		}
	}
}